package com.crawler.harbour.controller;

import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.dto.AppointmentDto;
import com.crawler.harbour.exception.SimpleException;
import com.crawler.harbour.utils.DateUtils;
import com.crawler.harbour.utils.UrlUtil;
import com.google.common.collect.Maps;

import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;
/**
 * 预约管理
 * @author czj
 *
 */
@RestController
@RequestMapping(value = "/crawler/fz")
public class FZReportController {

	private static final Logger LOGGER = LoggerFactory.getLogger(FZReportController.class);

	private Session loginGetSession(String userName, String password) {
		Session session = Requests.session();
		Map<String, String> queryMap = new HashMap<>();
		queryMap.put("remoteid", userName);
		queryMap.put("Action", "Login");
		queryMap.put("port", "FQCT");
		queryMap.put("remotekey", password);
		queryMap.put("userRole", "jms");
		session.post(UrlUtil.QINGZHOU_YUYUE_LOGIN + System.currentTimeMillis()).forms(queryMap).send().toTextResponse();
		return session;
	}

	/**
	 * 出口空箱进场预约接口
	 *
	 * @return
	 */
	@RequestMapping(value = "out_empty", method = RequestMethod.POST)
	public Object modckkxjcAdd(@RequestBody AppointmentDto appointmentDto) {
		Session session = loginGetSession(appointmentDto.getUserName(), appointmentDto.getPassword());
		Map<String, String> body = Maps.newHashMap();
		body.put("bl_no", appointmentDto.getLadingBillNo());
		body.put("cntr", appointmentDto.getContainerNo());

		Response<String> stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE_MODCKKXJC).forms().send()
				.toTextResponse();
		stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE_MODCKKXJC).forms().send().toTextResponse();
		Document document = Jsoup.parse(stringResponse.getBody());
		body.put("bkgcomp", document.select("#bkgcomp option[selected]").attr("value"));
		// 载货港
		body.put("pol", document.select("#pol").attr("value"));
		stringResponse = session.post(String.format(UrlUtil.QINGZHOU_YUYUE_CNTR,"cntr", body.get("cntr"),"","")).forms().send()
				.toTextResponse();
		String cntr = stringResponse.getBody();
		String[] eqp_typeAndopr = cntr.substring(cntr.indexOf("=") + 1, cntr.length()).split(":");
		
		
		stringResponse = session.post(String.format(UrlUtil.QINGZHOU_YUYUE_CNTR, body.get("cntr"))).forms().send()
				.toTextResponse();
		
		body.put("eqp_type", eqp_typeAndopr[0]);
		body.put("opr", eqp_typeAndopr[1]);
		// 出口船名
		body.put("out_vsl", "");
		// 出口航次
		body.put("out_vvd", appointmentDto.getShipTimer());
		// 箱类
		body.put("df", "");
		// 危险品等级
		body.put("haz_imco", "");
		// 联合国编码
		body.put("haz_unno", "");
		// 卸货港
		body.put("opd", appointmentDto.getDischargePort());
		// 交接单号
		body.put("eir_no", "");
		// 目的地
		body.put("dst", appointmentDto.getDischargePort());
		// 目的港
		body.put("pod", appointmentDto.getDischargePort());
		// 通风口
		body.put("tfk", "");
		String date = DateUtils.getDate("yyyy-MM-dd");
		// 预约时间
		body.put("BKG_DATE", date);
		body.put("BKG_TIME", "0000");
		// 至
		body.put("BKG_END_DATE", date);
		body.put("BKG_END_TIME", "2359");
		// 特别处理
		body.put("spc_hdlg", "");

		body.put("op", "add");
		body.put("vdf", "0");
		 stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE_MODCKKXJC_ADD).forms().send().toTextResponse();
		 stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE_TIJIAO).forms().send().toTextResponse();
		JSONObject exportResult = null;
		try {
			exportResult = JSONObject.parseObject(stringResponse.getBody());
			resultConvert(exportResult);
		} catch (Exception e) {
			throw new SimpleException("预约出错");
		}
		return exportResult;
	}

	/**
	 * 出口重箱进场预约接口
	 *
	 * @return
	 */
	@RequestMapping(value = "out_heavy", method = RequestMethod.POST)
	public Object modckzxyyAdd(@RequestBody AppointmentDto appointmentDto) {
		Session session = loginGetSession(appointmentDto.getUserName(), appointmentDto.getPassword());
		Map<String, String> body = Maps.newHashMap();
		// 提单号码
		body.put("bl_no", appointmentDto.getLadingBillNo());
		// 集装箱编号
		body.put("cntr", appointmentDto.getContainerNo());

		Response<String> stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE_MODCKZXYY).forms().send()
				.toTextResponse();
		Document document = Jsoup.parse(stringResponse.getBody());
		body.put("bkgcomp", document.select("SELECT[name='bkgcomp'] option[selected]").attr("value"));
		// 载货港
		body.put("pol", document.select("#pol").attr("value"));
		String cntr = stringResponse.getBody();
		String[] eqp_typeAndopr = cntr.substring(cntr.indexOf("=") + 1, cntr.length()).split(":");
		
		
		 Elements chirldren = document.select("#out_vsl");
		 ListIterator<Element> listIterator = chirldren.get(0).children().listIterator();
		 String shipName = "";
		 while(listIterator.hasNext()) {
			 Element next = listIterator.next();
			 if(next.html().startsWith(appointmentDto.getShipName()+":")) {
				 shipName = next.attr("value");
				 break;
			 }
		 }
		stringResponse =  session.post(String.format(UrlUtil.QINGZHOU_YUYUE_CNTR,"out_vvd", appointmentDto.getShipTimer(),
				"out_vsl",shipName
				)).forms().send()
				.toTextResponse();
		String df = stringResponse.getBody();
		df = df.substring(df.length()-1);
		
		body.put("eqp_type", eqp_typeAndopr[0]);
		body.put("opr", eqp_typeAndopr[1]);
		// 出口船名
		body.put("out_vsl", shipName);
		// 出口航次
		body.put("out_vvd", appointmentDto.getShipTimer());
		// 箱类
		body.put("df",df);
		// 箱型
		body.put("eqp_type", appointmentDto.getModel());
		// 持箱人
		body.put("opr", appointmentDto.getOwner());
		// 危险品等级
		body.put("haz_imco", "");
		// 联合国编码
		body.put("haz_unno", "");
		// 卸货港
		body.put("opd", appointmentDto.getDischargePort());
		body.put("opd1", appointmentDto.getDischargePort());
		// 交接单号
		body.put("eirNo", "");
		// 目的地
		body.put("dst", appointmentDto.getDischargePort());
		body.put("dst1", appointmentDto.getDischargePort());
		// 目的港
		body.put("pod", appointmentDto.getDischargePort());
		body.put("pod1", appointmentDto.getDischargePort());
		// 需要温度
		body.put("tempReq", "");
		// 件数
		body.put("cargo_pkg", "0");
		// 货重(公斤)
		body.put("cargo_wgt", "0");
		// 总重(公斤)
		body.put("grs_wgt", "0");
		// 铅封号
		body.put("seal",appointmentDto.getSealNo());
		// 验关体积
		body.put("cargo_cbm", "0");
		// 货物类
		body.put("cargo", "");
		// 货物描述
		body.put("cargoDesc", "");
		// 通风口
		body.put("tfk", "");
		// 特别处理
		body.put("spc_hdlg", "");
		// 超码
		body.put("oszInd", "");

		if (body.get("oszInd") != null && "1".equals(body.get("oszInd"))) {
			// 超出高
			if (body.get("oszHgt") == null) {
				body.put("oszHgt", "0");
			}
			// 超出前
			if (body.get("oszFrt") == null) {
				body.put("oszFrt", "0");
			}
			// 超出后
			if (body.get("oszRer") == null) {
				body.put("oszRer", "0");
			}
			// 超出左
			if (body.get("oszLft") == null) {
				body.put("oszLft", "0");
			}
			// 超出右
			if (body.get("oszRgt") == null) {
				body.put("oszRgt", "0");
			}
		} else {
			// 超出高
			body.put("oszHgt", "0");
			// 超出前
			body.put("oszFrt", "0");
			// 超出后
			body.put("oszRer", "0");
			// 超出左
			body.put("oszLft", "0");
			// 超出右
			body.put("oszRgt", "0");
		}

		body.put("vdf", df);
		body.put("op", "add");
		
		
		body.put("bkg", "");
		body.put("bkg_seq", "");
		body.put("wheresql", "");
		
		System.out.println(JSONObject.toJSONString(body));
		JSONObject exportResult = null;
		stringResponse =session.post(UrlUtil.QINGZHOU_YUYUE_MODCKZXYY_ADD).forms(body).send().toTextResponse();
		stringResponse = session.post(UrlUtil.QINGZHOU_YUYUE).forms(body).send().toTextResponse();
		try {
			if(stringResponse.getStatusCode() ==200) {
				String body2 = stringResponse.getBody();
				System.out.println(body2);
				String s1 ="<TD><div(\\s)*align=\"center\">正在预约处理中....(\\s)*<\\/div>(\\s)*<\\/TD>";
				Pattern pattern = Pattern.compile(s1);
				String prompt = null;
				Matcher m = pattern.matcher(body2);
				while (m.find()) {  
					prompt =m.group(0);
					System.out.println(prompt);
				}
				exportResult = new JSONObject();
				exportResult.put("result", "success");
				exportResult.put("message", prompt.split(prompt.split("\">",2)[1].toString()+",预约成功！"));
			}else {
				throw new RuntimeException();
			}
		} catch (Exception e) {
			throw new SimpleException("保存出错");
		}
		return exportResult;
	}

	private void resultConvert(JSONObject exportResult) {
		if (exportResult != null) {
			exportResult.put("result", exportResult.get("Result"));
			exportResult.put("message", exportResult.get("Message"));
			exportResult.remove("Result");
			exportResult.remove("Message");
		}
	}
	
}
